package com.igoal.web;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.igoal.dto.CommentDTO;
import com.igoal.entity.ComponentEnum;
import com.igoal.service.CommentService;
import com.igoal.service.UserManagerExt;
import com.igoal.utils.ConvertUtils;
import com.igoal.web.model.BaseModel;

@Controller
@RequestMapping("/ajax/comments.html")
public class AjaxCommentViewController extends BaseAjaxController {

	private Log logger = LogFactory.getLog(AjaxCommentViewController.class);

	private CommentService commentService;

	@Autowired
	public void setUserManagerExt(UserManagerExt userManagerExt) {
		this.userManagerExt = userManagerExt;
	}

	@Autowired
	public void setCommentService(CommentService commentService) {
		this.commentService = commentService;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String show(ModelMap modelMap, @RequestParam("componentId") String componentId, @RequestParam("component") String component,
			@RequestParam("componentOwner") String componentOwner, @RequestParam("lastComment") String lastComment) {
		BaseModel data = new BaseModel();
		initSessionInformation(data);
		
		List<CommentDTO> comments = new ArrayList<CommentDTO>();
		long id = ConvertUtils.toLong(componentId, -1l);
		long lastValue = ConvertUtils.toLong(lastComment, -1l);
		ComponentEnum com = ComponentEnum.valueOf(component);
		
		try {
			comments.addAll(commentService.loadAllCommentsBefore(id, com, lastValue));
		} catch (Exception e) {
			logger.error(e);
		}
		
		modelMap.addAttribute("comments", comments);
		modelMap.addAttribute("componentOwner", componentOwner);
		applyModel(modelMap, data);

		return getViewPrefix() + "ajaxCommentView";
	}
}
